﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;

namespace SharpCmd.EasterEggs
{
    internal class Snake
    {
        private const double CollisionDistance = 2;
        private const double RotationStep = Math.PI / 13;

        public Snake()
        {
            points = new List<PointF>();
            HeadLocation = new PointF(200, 350);
            points.Add(HeadLocation);
            angle = Math.PI / 2;
        }

        public List<PointF> points;
        public double angle;
        public DirectionEnum Direction;
        public PointF HeadLocation;
        private int jumpPositive = 0;
        const int JUMP_MAX = 4;

        /// <summary>
        /// Move for 1 timestep
        /// </summary>
        public bool Move()
        {
            if (jumpPositive > 0)
                jumpPositive--;
            Rotate();
            //add 1 new point 2 pixels away from our location
            const double Speed = 3;
            double dx = Math.Cos(angle) * Speed;
            double dy = Math.Sin(angle) * Speed;
            HeadLocation = new PointF(HeadLocation.X - (float)dx, HeadLocation.Y - (float)dy);
            //check for collisions
            var pts = points.Where(p => Math.Sqrt((p.X - HeadLocation.X) * (p.X - HeadLocation.X) + (p.Y - HeadLocation.Y) * (p.Y - HeadLocation.Y)) < CollisionDistance);
            if (pts.Count() > 0 && jumpPositive == 0)
                return false;
            points.Add(HeadLocation);
            return true;
        }

        /// <summary>
        /// jump for JUMP_MAX timesteps
        /// </summary>
        public void Jump()
        {
            jumpPositive = JUMP_MAX;
        }

        private void Rotate()
        {
            if (Direction == DirectionEnum.Left)
            {
                angle -= RotationStep;
            }
            else if (Direction == DirectionEnum.Right)
            {
                angle += RotationStep;
            }
        }

        public enum DirectionEnum
        {
            None,
            Left,
            Right
        }
    }
}
